package ch.fhnw.kosmonauten.client.gui;

import javax.swing.JOptionPane;

import ch.fhnw.kosmonauten.client.net.ServerConnection;
import ch.fhnw.kosmonauten.model.User;
import ch.fhnw.kosmonauten.model.Dossier;
import ch.fhnw.kosmonauten.net.Request;
import ch.fhnw.kosmonauten.net.Response;

public class LoadDossier extends javax.swing.JFrame {

	private ServerConnection sc;
	private User user;
	private Dossier dossier;
	private Dossier[] dossiers;
	private MainWindow main;
    /**
     * Creates new form LoadDossier
     */
    public LoadDossier(User user, MainWindow frame) {
    	this.user = user;
    	this.main = frame;
    	this.toFront();
		this.setAlwaysOnTop(true);
		this.setResizable(false);
        initComponents();
        this.setVisible(true);
        this.setTitle("Dossier laden");
        loadDossierFromServer(user);
    }

	private String[][] loadDossierFromServer(User user ) {
		sc = new ServerConnection();
		Response resp = sc.sendRequest(new Request(user,"getDossierList"));
		if (resp == null)
			new ErrorDialog(user.displayValue("mw82"));
		else if (resp.getContent() instanceof Dossier[]) 
		{	
			dossiers = (Dossier[]) resp.getContent();
			return DossiersToArray(dossiers);
		}
		else if (resp.getContent() == null )
		{
			new ErrorDialog(5, JOptionPane.ERROR_MESSAGE, user);
		}
		else
			new ErrorDialog(resp.getContent().toString());
		return new String[][]{{"Error"}};
	}
	
	private String[][] DossiersToArray(Dossier[] doses)
	{
		String[][] array = new String[doses.length][55];
		for(int index = 0; index < doses.length; index++)
		{//"DossierID", "Categoryname", "Dossiername", "Username", "Language", "Private", "Hexagram", "CreateDate", "EditDate"
			array[index][0] = Integer.toString(doses[index].getDossierID());
			array[index][1] = doses[index].getCategoryname();
			array[index][2] = doses[index].getDossierName();
			array[index][3] = doses[index].getUsername();
			array[index][4] = doses[index].getLanguagename();
			array[index][5] = Integer.toString(doses[index].getPrivacy());
			array[index][6] = doses[index].getHexagramname();
			array[index][7] = doses[index].getCreateDate();
			array[index][8] = doses[index].getEditDate();
		}
		return array;
	}

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
        		loadDossierFromServer(user),
            new String [] {
                "DossierID", "Categoryname", "Dossiername", "Username", "Language", "Private", "Hexagram", "CreateDate", "EditDate"
            }) 
        	{
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                true, false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setColumnSelectionAllowed(true);
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.DefaultListSelectionModel.SINGLE_SELECTION);

        jButton1.setText("Dossier laden");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1182, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    	if (this.jTable1.getSelectedRow() != -1)
    	{
    		this.dossier = dossiers[this.jTable1.getSelectedRow()];
    		main.setEmptyDossier();
    		//System.out.println(this.dossier.getQuestion());
    		
			main.initComponents();
			main.loadDossier(this.dossier);
			main.getSituationPanel2().showHexagram(this.dossier.getHexagramcode(), this.dossier);
			this.dispose();
    	}
    }


    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
}
